<?php
/**
 * 作者：李玉玲
 * 邮箱: 1332189576@qq.com
 * 日期: 14-11-5
 * 时间: 上午9:37
 */

namespace Api\Client;

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Decoder as JsonDecoder;
use Zend\Json\Json;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;

class ApiClient
{

    protected static $client=null;
    protected static $endpointHost='http://www.api.com';
    protected static $endpointNovel='/api/novel/%d';
    protected static $endpointNovels='/api/novel/all';
    public static function getNovel($id)
    {
        $url=self::$endpointHost.sprintf(self::$endpointNovel,$id);
        return self::doRequest($url);
    }
    public static function getNovels()
    {
        $url=self::$endpointHost.sprintf(self::$endpointNovels);
        return self::doRequest($url);
    }
    public static function postNovelContent($data)
    {
        $url=self::$endpointHost.self::$endpointNovel;
        return self::doRequest($url,$data,Request::METHOD_POST);
    }

    public static function getClientInstance()
    {
        if(self::$client===null){
            self::$client=new Client();
            self::$client->setEncType(Client::ENC_URLENCODED);
        }
        return self::$client;
    }


    public static function doRequest($url,array $postData=null,$method=Request::METHOD_GET)
    {
        $client=self::getClientInstance();
        $client->setUri($url);
        $client->setMethod($method);

        if($postData !==null){
            $client->setParameterPost($postData);
        }
        $response =$client->send();
        if($response->isSuccess()){
            return JsonDecoder::decode($response->getBody(),Json::TYPE_ARRAY);
        }else{
            $logger=new Logger();
            $logger->addWriter(new Stream('data\logs\apiclient.log'));
            $logger->debug($response->getBody());
            return false;
        }
    }
}